package com.lzxuni.modules.organization.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzxuni.common.annotation.SysLog;
import com.lzxuni.common.constant.LogConstant;
import com.lzxuni.common.exception.LzxException;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.validator.Assert;
import com.lzxuni.common.validator.ValidatorUtils;
import com.lzxuni.common.validator.group.AddGroup;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.PageData;
import com.lzxuni.modules.common.entity.PageParameter;
import com.lzxuni.modules.organization.entity.User;
import com.lzxuni.modules.organization.entity.UserImg;
import com.lzxuni.modules.organization.entity.UserOnLine;
import com.lzxuni.modules.organization.service.RoleService;
import com.lzxuni.modules.organization.service.UserImgService;
import com.lzxuni.modules.organization.service.UserService;
import com.lzxuni.modules.system.entity.Log;
import com.lzxuni.modules.system.service.LogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author:孙志强
 * @create:2018-05-02 21:32
 * @Modified BY:
 **/
@RestController
@RequestMapping("/LR_OrganizationModule/User")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserImgService userImgService;
    @Autowired
    private RoleService roleService;

	@Autowired
	private SessionDAO sessionDAO;

	@Autowired
	private LogService logService;

	@SysLog(categoryId = LogConstant.VIEWID,module = "系统管理-用户管理",operateType = LogConstant.VIEW)
	@RequestMapping("/Index")
	public ModelAndView list(HttpServletResponse response) throws Exception{
		ModelAndView mv = new ModelAndView("/LR_OrganizationModule/User/index");
		return mv;
	}

	@RequestMapping("/GetPageList")
	public Object GetPageList(String pagination, User user,String keyword) throws Exception {
		if(user!=null){
			if (StringUtils.isNotEmpty(keyword)) {
				user.setRealName(keyword);
			}
		}
		PageParameter pageParameter = JSON.parseObject(pagination, PageParameter.class);
		return R.ok().put("data", getPageData(userService.queryPage(pageParameter, user)));
	}

	@RequestMapping("/GetList")
	public Object getList(String companyId, String deptId) throws LzxException {
		User user = new User();
		user.setCompanyId(companyId);
		user.setDeptId(deptId);
		return R.ok().put("data", userService.list(new QueryWrapper<>(user)));
	}

	@SysLog(categoryId = LogConstant.VIEWID,module = "系统管理-在线用户",operateType = LogConstant.VIEW)
	@RequestMapping("/onLine/index")
	public ModelAndView onLine() throws Exception{
		ModelAndView mv = new ModelAndView("/LR_OrganizationModule/User/onLine/index");
		return mv;
	}
	@RequestMapping("/onLine/GetPageList")
	public Object getOnlineList(String pagination) throws LzxException {
		PageParameter pageParameter = JSON.parseObject(pagination, PageParameter.class);
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		List<UserOnLine> userOnlineList = new ArrayList<>();

		for(Session session:sessions){
			session.getStartTimestamp();
			SimplePrincipalCollection simplePrincipalCollection= (SimplePrincipalCollection) session.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
			if(simplePrincipalCollection!=null){
				User user = (User) simplePrincipalCollection.getPrimaryPrincipal();
				Log log = logService.queryLoginObjectByUserId(user.getUserId());
				String host = log.getHost();
				String browser = log.getBrowser();
				UserOnLine userOnLine = new UserOnLine();
				userOnLine.setUserId(user.getUserId());
				userOnLine.setUsername(user.getUsername());
				userOnLine.setRealName(user.getRealName());
				userOnLine.setMobile(user.getMobile());
				userOnLine.setCompanyId(user.getCompanyId());


				userOnLine.setCompanyId(user.getCompanyId());
				userOnLine.setStartTimestamp(session.getStartTimestamp());
				userOnLine.setLastAccessTime(session.getLastAccessTime());
				userOnLine.setIpAddress(log.getIpAddress());
				userOnLine.setIpAddressName(log.getIpAddressName());


				String os = host.split("主机名称：")[0];
				userOnLine.setOs(os.substring(5, os.length() - 1));
				userOnLine.setBrowser(browser.split(" --- ")[1]);
				userOnlineList.add(userOnLine);
			}
		}

		//排序
		List<UserOnLine> userOnlineListNew = new ArrayList<>();
		String sidx = pageParameter.getSidx();
		String sord = pageParameter.getSord();
		if(StringUtils.isEmpty(sidx)){
			sidx = "lastAccessTime";
		}
		if(sidx.equalsIgnoreCase("Username")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getUsername)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getUsername).reversed()).collect(Collectors.toList());
			}

		}else if(sidx.equalsIgnoreCase("RealName")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getRealName)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getRealName).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("Mobile")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getMobile)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getMobile).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("CompanyId")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getCompanyId)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getCompanyId).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("IpAddress")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getIpAddress)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getIpAddress).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("IpAddressName")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getIpAddressName)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getIpAddressName).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("Browser")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getBrowser)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getBrowser).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("Os")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getOs)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getOs).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("StartTimestamp")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getStartTimestamp)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getStartTimestamp).reversed()).collect(Collectors.toList());
			}
		}else if(sidx.equalsIgnoreCase("LastAccessTime")){
			if(sord.equalsIgnoreCase("asc")){
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getLastAccessTime)).collect(Collectors.toList());
			}else{
				userOnlineListNew=userOnlineList.stream().sorted(Comparator.comparing(UserOnLine::getLastAccessTime).reversed()).collect(Collectors.toList());
			}
		}
//		Collections.sort(userOnlineList);
		PageData pageData = new PageData() ;
		pageData.setRows(userOnlineListNew);
		pageData.setTotal(1);
		pageData.setPage(1);
		pageData.setRecords((long) userOnlineList.size());
		pageData.setCosttime(10);
		return R.ok().put("data", pageData);


//		String loginName=token.getUsername();
//		Session currentSession = null;
//		for(Session session:sessions){
//			if(loginName.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY))) {
//				session.setTimeout(0);//设置session立即失效，即将其踢出系统
//				break;
//			}
//		}
	}


	@RequestMapping("/Form")
	public ModelAndView insert() {
		ModelAndView mv = new ModelAndView("/LR_OrganizationModule/User/form");
		return mv;
	}

	//插入处理
	@SysLog(categoryId = LogConstant.OPERATEID,module = "系统管理-用户管理",operateType = LogConstant.INSERT)
	@RequestMapping("/SaveForm")
	public Object insert(String keyValue, User user) {
		user.setUserId(keyValue);
		if (StringUtils.isEmpty(user.getUserId())) {
			Assert.isBlank(user.getUsername(), "账号不能为空");
			ValidatorUtils.validateEntity(user, AddGroup.class);
			userService.insert(getUser(), user);
			return R.ok("保存成功");
		} else {
//			userService.update(getUser(),user);
			userService.update(user, new QueryWrapper<User>().eq("user_id", keyValue));
			return R.ok("修改成功");
		}
	}

	@RequestMapping("/ExistAccount")
	public Object existAccount(String keyValue, String username) {
		if (StringUtils.isEmpty(keyValue)) {
			int count = userService.count(new QueryWrapper<User>().eq("username", username));
			if (count > 0) {
				return R.ok("响应成功").put("data", false);
			}
		}
		return R.ok("响应成功").put("data", true);
	}

	//删除
	@SysLog(categoryId = LogConstant.OPERATEID,module = "系统管理-用户管理",operateType = LogConstant.DELETE)
	@RequestMapping("/DeleteForm")
	public Object delete(String keyValue) {
		userService.delete(keyValue);
		return R.ok("删除成功");
	}

	//更改用户状态
	@SysLog(categoryId = LogConstant.OPERATEID,module = "系统管理-用户管理",operateType = "更改用户状态")
	@RequestMapping("/UpdateState")
	public Object updateState(@RequestParam("keyValue") String userId, Integer state) {
		User user = new User();
		user.setUserId(userId);
		user.setEnabledMark(state);
		userService.update(user, new QueryWrapper<User>().eq("user_id", userId));
		return R.ok("修改成功");
	}

	//重置密码
	@SysLog(categoryId = LogConstant.OPERATEID,module = "系统管理-用户管理",operateType = "重置密码")
	@RequestMapping("/ResetPassword")
	public Object resetPassword(@RequestParam("keyValue") String userId) {
		userService.resetPassword(userId);
		return R.ok("重置成功");
	}

	// 获取用户session页面
	@RequestMapping("/GetUserInfo")
	public Object getUserInfo() {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		return R.ok().put("data", user);
//		ModelAndView mv = new ModelAndView("/Login/GetUserInfo");
//		return mv;
	}

	@RequestMapping("/GetMap")
	public Object getMap() {
		ModelAndView mv = new ModelAndView("/LR_OrganizationModule/User/getMap");
		return mv;
	}

	@RequestMapping("/GetImg")
	public void GetImg(HttpServletRequest request, HttpServletResponse response, String userId) {
		try {
			if (StringUtils.isEmpty(userId)) {
				userId = getUserId();
			}
			InputStream inputStream;
			//1 默认，有头像，2 男3女4没有性别
			int type = 0;
			//如果用户设置了头像
			UserImg userImg = userImgService.getById(userId);
			if (userImg != null) {
				type = 1;
			} else {
				//如果用户没设置头像
				//用户有性别
				if (StringUtils.isNotEmpty(getUser().getGender())) {
					//男
					if (getUser().getGender().equals("1")) {
						type = 2;
					} else {
						type = 3;
					}
				} else {
					type = 4;
				}
			}
			switch (type) {
				case 1:
					inputStream = new ByteArrayInputStream(userImg.getImg());
					break;
				case 2:
					inputStream = new ClassPathResource("static/Content/images/UserCard02.png").getInputStream();
					break;
				case 3:
					inputStream = new ClassPathResource("static/Content/images/UserCard01.png").getInputStream();
					break;
				case 4:
					inputStream = new ClassPathResource("static/Content/images/UserCard01.png").getInputStream();
					break;
				default:
					inputStream = new ClassPathResource("static/Content/images/UserCard01.png").getInputStream();
					break;
			}
			writeImg(response, inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//用户没性别
	}

	private void writeImg(HttpServletResponse response, InputStream sbs) throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成图片验证码
		BufferedImage image = ImageIO.read(sbs);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "png", out);
	}
	//========================杨国营=====流程委托=====UI素材==============================================
	@RequestMapping("/SelectOnlyForm")
	public ModelAndView Form() {
		ModelAndView mv = new ModelAndView("LR_OrganizationModule/User/SelectOnlyForm");
		return mv;
	}

    // 根据地址查询出公司并查询出公司下所属用户 -- 刘振鹏
    @RequestMapping("/GetTree")
    public Object GetListByAreaId() {
        return R.ok().put("data",userService.getTree());
    }
}
